import { Post, PostType } from '@prisma/client';
import { TX } from '../db';

type CreateData = {
  title: string;
  content: string;
  collectionId: bigint;
  userId: bigint;
  type: PostType;
  dedupKey: string;
  tagIds: string[];
};

async function create(tx: TX, data: CreateData): Promise<Post> {
  const now = new Date();
  return tx.post.create({
    data: {
      title: data.title,
      content: data.content,
      collectionId: data.collectionId,
      userId: data.userId,
      type: data.type,
      createTime: now,
      deleteTime: null,
      updateTime: now,
      dedupKey: data.dedupKey,
      tagIds: data.tagIds,
    },
  });
}

async function findById(tx: TX, id: bigint): Promise<Post | null> {
  return tx.post.findFirst({ where: { id } });
}

async function findByIdAndUserId(tx: TX, id: bigint, userId: bigint): Promise<Post | null> {
  return tx.post.findFirst({ where: { id, userId } });
}

async function findByUserId(tx: TX, userId: bigint, limit: number): Promise<Post[]> {
  return tx.post.findMany({
    where: { userId },
    take: limit,
    orderBy: { id: 'desc' },
  });
}

async function findByUserIdAndCollectionId(tx: TX, userId: bigint, collectionId: bigint): Promise<Post[]> {
  return tx.post.findMany({ where: { userId, collectionId } });
}

type UpdateData = {
  title: string;
  content: string;
  tagIds: string[];
  userId: bigint;
  id: bigint;
};

async function update(tx: TX, { id, userId, title, content, tagIds }: UpdateData) {
  const now = new Date();
  await tx.post.update({
    where: { id, userId },
    data: { title, content, updateTime: now, tagIds },
  });
}

export const postService = {
  create,
  findById,
  findByIdAndUserId,
  findByUserId,
  findByUserIdAndCollectionId,
  update,
};
